import React, { useRef, useState } from 'react';
import IconMessage from '@/components/Icons/IconMessage';
import IconDeleted from '@/components/Icons/IconDeleted';
import IconEdit from '@/components/Icons/IconEdit';
import classNames from 'classnames';
import { useDispatch } from 'react-redux';
import { delHistoryChatAction } from '@/store/actions/chat';
import { useRouter } from 'next/router';

type itemTypes = {
  id?: string;
  title?: string;
  activate?: boolean;
  onClickEdit?: () => void;
};

const HistoryItem: React.FC<itemTypes> = ({ id, title, activate = false, onClickEdit }) => {
  const dispatch = useDispatch();

  const router = useRouter();

  const [hovered, setHovered] = useState<boolean>(false);

  const idRef = useRef<HTMLDivElement>(null);

  const handleOnclick = () => {
    router.push({
      pathname: '/chat',
      query: { id: idRef.current?.id },
    });
  };

  //   hover
  const handleMouseEnter = () => {
    setHovered(true);
  };

  const handleMouseLeave = () => {
    setHovered(false);
  };

  // del chat history item
  const delItem = () => {
    if (idRef.current) {
      dispatch(delHistoryChatAction(idRef.current.id));
    }
  };

  return (
    <div
      id={id}
      ref={idRef}
      className={classNames(
        'flex items-center border border-transparent rounded-lg w-full h-8 px-1 justify-items-stretch my-1 hover:bg-indigo-100 cursor-pointer justify-between',
        activate ? 'bg-indigo-200' : '',
      )}
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
    >
      <div className="flex items-center " onClick={handleOnclick}>
        <IconMessage clasName="h-4 w-4 mr-2 fill-indigo-500" color={hovered || activate ? '#1296db' : ''} />
        <span className="w-24 h-7 leading-7 text-slate-400 hover:text-sky-500 text-sm font-semibold truncate ...">
          {title}
        </span>
      </div>

      <div className="flex items-center">
        <IconEdit
          clasName={classNames('h-4 w-4 mr-2 ', hovered || activate ? '' : 'invisible')}
          onClick={onClickEdit}
        />
        <IconDeleted clasName={classNames('h-4 w-4  ', hovered || activate ? '' : 'invisible')} onClick={delItem} />
      </div>
    </div>
  );
};

export default HistoryItem;
